package com.totobox.apps.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.channels.FileChannel;

import android.util.Log;

/**
 * @author gundallove
 * @email gundallove@gmail.com
 */
public class FileUtils {

    /**
     * The number of bytes in a kilobyte.
     */
    public static final long ONE_KB = 1024;

    /**
     * The number of bytes in a megabyte.
     */
    public static final long ONE_MB = ONE_KB * ONE_KB;
    
    /**
     * The number of bytes in a 50 MB.
     */
    private static final long FIFTY_MB = ONE_MB * 50;
    
    /**
     * The default buffer size to use for 
     * {@link #copyLarge(InputStream, OutputStream)}
     * and
     * {@link #copyLarge(Reader, Writer)}
     */
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    
	//데이터 파일을 저장한다.
	public static void saveFile(String file , String string){
		
		BufferedWriter bw = null;
		try {
			bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
			bw.write(string);
			bw.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try{if(bw!=null)bw.close();}catch(Exception e){}
		}
	}
	
	//데이터 파일을 읽어 온다.
	public static String readFile(String file){
		
		String line="";
		BufferedReader br = null;
		try{
			File f = new File(file);
			if(f.exists()){
				br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
	    		line = br.readLine();
			}
    	} catch (Exception e) {
    		return "";
		} finally {
    		try{if(br!=null)br.close();}catch(Exception e){}
    	}
		
		return line;
	}
	
	//디렉토리 생성
	public static void setMakeDir(String makeDir) {
    	
    	try{
			File dir = new File(makeDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
    	}catch(Exception e){
    		Log.d("mkdirs : ",e.getMessage());
    	}
    	
    }

	//폴더 밑의 파일 삭제
	public static boolean deleteFile(String partDir){
		
		File path = new File(partDir);

		try{
	    	String[] children = path.list();
	    	if (children != null) {
		    	for (int i=0; i<children.length; i++) {
		    		String filename = children[i];
		    		File f = new File(partDir + filename);
			    	if (f.exists()) {
			    		f.delete();
			        }
		        }//for
	        }//if
		}catch(Exception e){
			return false;
		}
    	return true;
	}
	
	/**
	 * <pre>
	 * 파일 폴더 삭제
	 * @param path
	 * @return
	 * boolean
	 * </pre>
	 */
	public static boolean deleteFileDir(File path) {
		
		if(!path.exists()) {
			return false;
		}
		
		File[] files = path.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				deleteFileDir(file);
			} else {
				file.delete();
			}
		}
		return path.delete();
	}
	
	public static void copyURLToFile(InputStream is , File dest){
		
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		
		try{
			
			int i;
			byte[] b = new byte[2048];
			
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(new FileOutputStream(dest));
			
			while((i=bis.read(b)) != -1){
				bos.write(b,0,i);
			}
			bos.flush();
			
		}catch(Exception e){
			//Util.LOG("copyURLToFile : "+e.getMessage()+"\n");
		}
		finally{
			try{ if(bis!=null) bis.close();}catch(Exception e){}
			try{ if(bos!=null) bos.close();}catch(Exception e){}
		}
	}
	
	public static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            input  = fis.getChannel();
            output = fos.getChannel();
            long size = input.size();
            long pos = 0;
            long count = 0;
            while (pos < size) {
                count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);
                pos += output.transferFrom(input, pos, count);
            }
        } finally {
            closeQuietly(output);
            closeQuietly(fos);
            closeQuietly(input);
            closeQuietly(fis);
        }

        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from '" +
                    srcFile + "' to '" + destFile + "'");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }
   
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }
    
	/**
	 * 파일명 생성
	 * @param wholePath
	 * @return
	 */
	public static String getFileName(String wholePath)
    {
        String name=null;
        int start,end;
        start=wholePath.lastIndexOf('/');
        end=wholePath.length();     //lastIndexOf('.');
        name=wholePath.substring((start+1),end);
        return name;
    }
}
